import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  Select,
  Space,
  Table,
  TreeSelect
} from 'antd';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  manageArriveAdd,
  manageArriveGet,
  manageArriveUpdate
} from '@/services/bizApi/jingyingdaohuoguanlibiaojiekou';

import { BizObject } from './';
import Plan, { PlanRef } from './plan';

type DataSourceType = {
  key: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const plan = useRef<PlanRef>(null);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [dataSource, setDataSource] = useState<BIZAPI.ManageNeedEntity[]>([]);
  const treeDict = useRef<Record<number, DataNode>>({});

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const manageArrive = useRequest(
    async (id: string) => {
      const res = await manageArriveGet({ id });
      const data = res?.data;
      // 回填数据
      form.setFieldsValue({
        ...res?.data,
        applyTime: res?.data?.applyTime ? dayjs(res?.data?.applyTime) : undefined
      });
      setDataSource(data?.detailEntityList || []);
    },
    {
      manual: true
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      if (!dataSource?.length) {
        store.app?.message.info('请添加采购计划关联');
        return;
      }
      const query = {
        ...values,
        applyTime: values?.planTime ? dayjs(values?.applyTime).format('YYYY-MM-DD') : undefined,
        detailEntityList: dataSource
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? manageArriveUpdate(query) : manageArriveAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            manageArrive.run(arg?.rowData?.id as unknown as string);
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="验收意见"
          name="opinion"
          rules={[
            {
              required: true,
              message: '请输入验收意见'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入验收意见" />
        </Form.Item>
        <Form.Item
          label="附件"
          name="fileId"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload
            // base64
            //  accept="image/*"
            maxCount={1}
          >
            <Button>上传</Button>
          </Upload>
        </Form.Item>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            width: '100%',
            padding: '20px 24px 10px'
          }}
        >
          <Button
            type="primary"
            disabled={args?.type === 'detail'}
            onClick={() => {
              plan.current?.open({
                onSuccess: (rows) => {
                  form?.setFieldsValue({
                    applyUserId: rows?.[0]?.applyUserId,
                    purchaseAmount: rows?.[0]?.purchaseAmount,
                    planId: rows?.[0]?.id,
                    applyTime: rows?.[0]?.applyTime ? dayjs(rows?.[0]?.applyTime) : undefined
                  });
                  setDataSource(rows?.[0]?.detailEntityList || []);
                }
              });
            }}
          >
            采购计划关联
          </Button>
        </div>
        <Form.Item
          label="申请部门"
          name="applyDeptId"
          rules={[
            {
              required: false,
              message: '请选择申请部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            disabled
            placeholder="请选择申请部门"
            allowClear
          />
        </Form.Item>
        <Form.Item
          label="申请日期"
          name="applyTime"
          rules={[
            {
              required: false,
              message: '请选择申请日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择申请日期" style={{ width: '100%' }} disabled />
        </Form.Item>
        <Form.Item
          label="申请人"
          name="applyUserId"
          rules={[
            {
              required: false,
              message: '请选择申请人'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择申请人"
            showSearch={true}
            optionFilterProp="label"
            disabled
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Form.Item>
        <Form.Item
          label="采购金额"
          name="purchaseAmount"
          rules={[
            {
              required: false,
              message: '请输入采购金额'
            }
          ]}
        >
          <Input placeholder="请输入采购金额" disabled />
        </Form.Item>
        <Form.Item
          label="planId"
          name="planId"
          hidden
          rules={[
            {
              required: false,
              message: '请输入planId'
            }
          ]}
        >
          <Input placeholder="请输入planId" disabled />
        </Form.Item>
      </Form>
      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '名称',
            dataIndex: 'name'
          },
          {
            title: '数量',
            dataIndex: 'number'
          },
          {
            title: '金额',
            dataIndex: 'money'
          }
        ]}
        dataSource={dataSource}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        // {...table.tableProps}
        pagination={
          {
            // ...table.tableProps.pagination,
            // showTotal: (total) => `共 ${total} 条`,
            // showQuickJumper: true,
            // showSizeChanger: true,
            // pageSizeOptions: ['10', '20', '50', '100']
          }
        }
      />
      {/* end表格 */}
      <Plan ref={plan} />
    </Drawer>
  );
};

export default forwardRef(Edit);
